package HttpServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Map;

@WebServlet(urlPatterns = {"/upload3"})
@MultipartConfig(location = "C:\\Users\\78733\\Desktop\\Experiment3\\src\\main\\webapp\\image")// location改为本地的绝对路径
public class informationservlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Map<String,String> userName = (Map<String, String>) request.getSession().getAttribute("userName");
        String username=userName.get("用户名");

        // 获取请求项，封装成Part对象
        // request.getPart方法的传参为前端页面from表单的input文件组件的name值
        Part part = request.getPart("file");

        // part.getSubmittedFileName()方法获取上传文件的文件名
        String fileName = part.getSubmittedFileName();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 根据@MultipartConfig的location配置的目录上传文件，直接传参文件名即可。

        part.write(username+suffix);

        response.getWriter().write("头像上传成功！");

    }

}
